package com.xudow.app.newui.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.umeng.message.PushAgent;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.module.DynamicStateFragment;
import com.xudow.app.model.SimpleUser;
import com.xudow.app.newui.PreLoginActivity;
import com.xudow.app.newui.base.BaseUiActivity;
import com.xudow.app.newui.fragment.CourseFragment;
import com.xudow.app.newui.fragment.ProfileFragment;
import com.xudow.app.newui.fragment.ToolKitFragment;
import com.xudow.app.newui.zutils.SystemBarTintManager;
import com.xudow.app.service.SessionService;
import com.xudow.app.ui.LoginActivity;
import com.xudow.app.ui.task.LoginTask;
import com.xudow.app.ui.task.SearchLevalTask;
import com.xudow.app.util.NetworkUtils;
import com.xudow.app.util.PrefUtils;
import com.xudow.app.util.UpdateManager;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 作者：LownChen on 2016/5/25 13:25
 */
public class HomeActivity extends BaseUiActivity implements View.OnClickListener{
    private static final String TAG_ONE = "one";
    private static final String TAG_TWO = "two";
    private static final String TAG_THREE = "three";
    private static final String TAG_FOUR = "four";

    private FragmentManager fragmentManager;
    /**
     * 标示是否为按两次返回键退出
     */
    private static boolean isExitStatus = false;

    @BindView(R.id.home_one_ll)
    LinearLayout home_one_ll;

    @BindView(R.id.home_two_ll)
    LinearLayout home_two_ll;

    @BindView(R.id.home_three_ll)
    LinearLayout home_three_ll;

    @BindView(R.id.home_four_ll)
    LinearLayout home_four_ll;

    @BindView(R.id.home_one_tv)
    TextView home_one_tv;

    @BindView(R.id.home_one_img)
    ImageView home_one_img;

    @BindView(R.id.home_two_tv)
    TextView home_two_tv;

    @BindView(R.id.home_two_img)
    ImageView home_two_img;

    @BindView(R.id.home_three_tv)
    TextView home_three_tv;

    @BindView(R.id.home_three_img)
    ImageView home_three_img;

    @BindView(R.id.home_four_tv)
    TextView home_four_tv;

    @BindView(R.id.home_four_img)
    ImageView home_four_img;

    /**
     * 定位开始
     */
    private LocationClient mLocationClient;
    private NotifyLocationListener listener;
    SystemBarTintManager tintManager;
    MyBroadcastReceiver br;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentManager = getSupportFragmentManager();
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);

        // 4.4及以上版本开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }
        // 自定义颜色
        initWindow2();

        //检测更新
        if (NetworkUtils.isNetWorkConnected(this)) {
            // 检查新版本
            UpdateManager.getUpdateManager().checkAppUpdate(this, true);

        }
        // 开启服务 检查Session时候过期
        startService(new Intent(this, SessionService.class));
//        PushAgent.getInstance(this).enable();

        try {

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.dsw.data");
            br= new MyBroadcastReceiver();
        registerReceiver(br, intentFilter);
        }catch (Exception e){
            Log.i("MyBroadcastReceiver","广播蹦了");
        }
    }

    class MyBroadcastReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            String data = intent.getStringExtra("data");

            if(twoFragment==null){
//                home_two_ll.setClickable(true);

                initWindow2();
                clearViewState();
                home_two_img.setImageResource(R.mipmap.btn_two_p);
                home_two_tv.setTextColor(Color.parseColor("#55c13d"));
                switchFragment(4);

            }else{

                twoFragment.updategrids();
            }
//            Toast.makeText(context, data, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(br);
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
    @Override
    protected void onStart() {
        super.onStart();
        //开始定位
        listener = new NotifyLocationListener();
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(listener);
        mLocationClient.start();


    }


    public class NotifyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            XApplication application = (XApplication) getApplication();
            application.latitude = location.getLatitude();
            application.longitude = location.getLongitude();

            //  Log.e("Location","latitude="+application.latitude+"--longitude="+application.longitude );
        }
    }

    @Override
    protected void initData() {
        switchFragment(0);

    }





    @Override
    protected void initListener() {
        home_one_ll.setOnClickListener(this);
        home_two_ll.setOnClickListener(this);
        home_three_ll.setOnClickListener(this);
        home_four_ll.setOnClickListener(this);

    }


    @Override
    public void onClick(View view) {


        switch (view.getId()) {

            case R.id.home_one_ll: // 动态
                initWindow2();
                clearViewState();
                home_one_img.setImageResource(R.mipmap.btn_one_p);
                home_one_tv.setTextColor(Color.parseColor("#55c13d"));
                switchFragment(0);

                break;

            case R.id.home_two_ll: // 课程

                initWindow2();
                clearViewState();
                home_two_img.setImageResource(R.mipmap.btn_two_p);
                home_two_tv.setTextColor(Color.parseColor("#55c13d"));
                switchFragment(1);

                break;

            case R.id.home_three_ll: // 工具箱
                initWindow2();
                clearViewState();
                home_three_img.setImageResource(R.mipmap.btn_three_p);
                home_three_tv.setTextColor(Color.parseColor("#55c13d"));
                switchFragment(2);

                break;

            case R.id.home_four_ll: // 我的
                if (!handleLogin()){//如果未登录跳出
                    break;
                }
                initWindow();
                clearViewState();
                home_four_img.setImageResource(R.mipmap.btn_four_p);
                home_four_tv.setTextColor(Color.parseColor("#55c13d"));
                switchFragment(3);

                break;

        }
    }

    /**
     * 清楚图片和文字选中状态
     */
    private void clearViewState() {
        home_one_img.setImageResource(R.mipmap.btn_one_n);
        home_two_img.setImageResource(R.mipmap.btn_two_n);
        home_three_img.setImageResource(R.mipmap.btn_three_n);
        home_four_img.setImageResource(R.mipmap.btn_four_n);

        home_one_tv.setTextColor(Color.parseColor("#969696"));
        home_two_tv.setTextColor(Color.parseColor("#969696"));
        home_three_tv.setTextColor(Color.parseColor("#969696"));
        home_four_tv.setTextColor(Color.parseColor("#969696"));

    }
//    SystemBarTintManager tintManager;
DynamicStateFragment oneFragment;
    CourseFragment twoFragment;
    ToolKitFragment threeFragment;
    ProfileFragment fourFragment;
    /**
     * 显示或隐藏fragment
     *
     * @param tag 标识
     */

    private void switchFragment(int tag) {
//         oneFragment = fragmentManager.findFragmentByTag(TAG_ONE);
//         twoFragment = fragmentManager.findFragmentByTag(TAG_TWO);
//         threeFragment = fragmentManager.findFragmentByTag(TAG_THREE);
//         fourFragment = fragmentManager.findFragmentByTag(TAG_FOUR);

        FragmentTransaction  transaction = fragmentManager.beginTransaction();

        hihtFragment(transaction);
           switch (tag){
               case 0:
                   if (oneFragment == null) {

                       oneFragment = new DynamicStateFragment(); // 动态
                       transaction.add(R.id.fl_home_fragment_container, oneFragment);

                   } else {
                       transaction.show(oneFragment);
                   }
                   break;
               case 1:
                   if (twoFragment == null) {
                       twoFragment = new CourseFragment(); // 课程
                       transaction.add(R.id.fl_home_fragment_container,  twoFragment);

                   } else {
                       transaction.show(twoFragment);
                   }
                   break;
               case 2:
                   if (threeFragment == null) {
                       threeFragment = new ToolKitFragment(); // 工具箱
                       transaction.add(R.id.fl_home_fragment_container,  threeFragment);

                   } else {
                       transaction.show(threeFragment);
                   }
                   break;
               case 3:
                   if (fourFragment == null) {
                       fourFragment = new ProfileFragment();//我
                       transaction.add(R.id.fl_home_fragment_container, fourFragment);

                   } else {
                       transaction.show(fourFragment);
                   }
                   break;
               case 4:
                   if (twoFragment == null) {
                       twoFragment = new CourseFragment(); // 课程
                       transaction.add(R.id.fl_home_fragment_container,  twoFragment);
                       twoFragment.updategrids();

                   } else {
                       transaction.show(twoFragment);
                       twoFragment.updategrids();
                   }
                   break;
           }

        transaction.commitAllowingStateLoss();
    }

    private void hihtFragment(FragmentTransaction transaction) {

        if (oneFragment != null) {
            transaction.hide(oneFragment);
        }
        if (twoFragment != null) {
           transaction.hide(twoFragment);
        }

        if (threeFragment != null) {
            transaction.hide(threeFragment);
        }

        if (fourFragment != null) {
           transaction.hide(fourFragment);
        }

    }

    private void initWindow(){

        tintManager.setTintColor(Color.parseColor("#6DB93D"));

    }
    private void initWindow2(){

        tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setNavigationBarTintEnabled(true);

        tintManager.setTintColor(Color.parseColor("#cbcbcc"));


    }
    /**
     *判断登录操作
     * 已经登录 true
     * 未登录 false
     */
    private boolean handleLogin(){
        if (!application.isLogin()) {
            startActivity(new Intent(this, PreLoginActivity.class));

            return false;
        }
        return true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.stop();
        mLocationClient = null;
        listener = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 双击退出
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            exit();
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }
    /**
     * 退出方法
     */
    private void exit() {
        if (!isExitStatus) {
            isExitStatus = true;

            String exitPrompt = getString(R.string.common_exit_prompt);
            Toast.makeText(getApplicationContext(), exitPrompt, Toast.LENGTH_SHORT).show();

            exitKeydownHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
        }
    }

    /**
     * 是否是按两次返回键退出Handler
     */
    Handler exitKeydownHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExitStatus = false;
        }
    };
}
